/* 
 * This program is free software; you can redistribute it and/or modify 
 * it under the terms of the GNU General Public License as published by 
 * the Free Software Foundation; either version 3 of the License, or 
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful, but 
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY 
 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 
 * for more details.
 * 
 * You should have received a copy of the GNU General Public License along 
 * with this program; if not, write to the Free Software Foundation, Inc., 
 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 */


#include <QPainter>
#include "threadoverviewdelegate.h"

ThreadOverviewDelegate::ThreadOverviewDelegate(QObject* parent) : QStyledItemDelegate(parent),
	m_iconWidth(48), m_iconHeight(48)
{
}

ThreadOverviewDelegate::~ThreadOverviewDelegate()
{
}

void ThreadOverviewDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const
{
	Q_ASSERT(index.isValid());
	QStyleOptionViewItemV4 opt(option);
	initStyleOption(&opt, index);
	painter->save();
	QStyle *style = opt.widget->style();

	style->drawPrimitive(QStyle::PE_PanelItemViewItem, &opt, painter, opt.widget);

	if (option.state & QStyle::State_Selected)
		painter->setPen(QPen(option.palette.brush(QPalette::HighlightedText), 0));

	QRect r = option.rect;
	r.setWidth(m_iconWidth);
	r.setHeight(m_iconHeight);
	r.translate(2, 2);
	QPixmap p = opt.icon.pixmap(m_iconWidth, m_iconHeight);
	int offset = 2;
	if(!p.isNull())
	{
		if(p.size().height() != p.size().width())
			r.adjust(0, (r.height() - p.size().height()) / 2, 0, -(r.height() - p.size().height()) / 2);
		painter->drawPixmap(r, p);
		offset += m_iconWidth;
	}
	r = option.rect;
	r.adjust(offset + 2, 0, 0, 0);
	int strings = (m_iconHeight - 4) / opt.fontMetrics.lineSpacing();
	QString text = opt.text.section('\n', 0, strings);
	painter->drawText(r, Qt::AlignVCenter, text);

	if ((option.state & QStyle::State_HasFocus) == 0 || !option.rect.isValid())
	{
		painter->restore();
        return;
	}
    QStyleOptionFocusRect o;
    o.QStyleOption::operator=(option);
    o.rect = option.rect;
    o.state |= QStyle::State_KeyboardFocusChange;
    o.state |= QStyle::State_Item;
    QPalette::ColorGroup cg = (option.state & QStyle::State_Enabled)
                              ? QPalette::Normal : QPalette::Disabled;
    o.backgroundColor = option.palette.color(cg, (option.state & QStyle::State_Selected)
                                             ? QPalette::Highlight : QPalette::Window);
	style->drawPrimitive(QStyle::PE_FrameFocusRect, &o, painter, opt.widget);
	painter->restore();
}

QSize ThreadOverviewDelegate::sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const
{
	return QSize(option.rect.width(), m_iconHeight + 4);
}

